package com.yeyaomai.dksns.flowis.dao.impl;

import org.springframework.data.mongodb.core.mapreduce.GroupBy;
import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.yeyaomai.dksns.flowis.dao.EngineDao;
import com.yeyaomai.dksns.flowis.dao.MongoDBBasicDao;
import com.yeyaomai.dksns.flowis.domain.Engine;
import com.yeyaomai.dksns.flowis.util.CollectionNames;

/**
 * 搜索引擎Dao层实现
 * @author sun_shan
 * 
 */
@Component
public class EngineDaoImpl extends MongoDBBasicDao<Engine> implements EngineDao {

	@Override
	public void insertEngine(Engine engine) {
		super.save(engine);
	}

	@Override
	public Engine getEngineById(Integer id) {
		return super.findOne(Criteria.where("id").is(id), Engine.class);
	}

	@Override
	public GroupByResults<Engine>findEngineByEngineNameAndTimeBetween(String from,String to) {
		String mapFunction="{searchTime: 0, keyWordNumber: 0, uniqueVistor: 0, ip: 0}";
		String reduceFunction="function(doc, prev) {prev.engineName,prev.searchTime+=1,prev.keyWordNumber+=1,prev.uniqueVistor+=1,prev.ip+=1}";
		return super.group(Criteria.where("create_time").gte(from).lte(to),CollectionNames.ENGINECOLLECTION, GroupBy.key("engineName").initialDocument(mapFunction).reduceFunction(reduceFunction), Engine.class);
	}

	@Override
	public long countSearchTimeByCreateTime(String createTime) {
		return mongoTemplate.count(new Query(Criteria.where("create_time").is(createTime)), Engine.class);
	}


	@Override
	public long countSearchTimeByEngineNameAndCreateTime(String engineName,String createTime) {
		return mongoTemplate.count(new Query(Criteria.where("engineName").is(engineName).and("create_time").is(createTime)), Engine.class); 
	}

}
